package com.bjc.scheduler.elasticjob.springboot.config;

import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.base.CoordinatorRegistryCenter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * @program: elastic-job-springboot
 * @description:
 * @author: bjc
 * @create: 2021-08-15 21:08
 */
@Configuration
public class ElasticJobConfig {

//    @Autowired
//    private SimpleJob fileBackupJob;

    @Autowired
    private SimpleJob fileBackupJobDb;

    @Autowired
    private CoordinatorRegistryCenter coordinatorRegistryCenter;

    /**
     * 配置人们五详细信息
     * @param jobClass                任务执行类
     * @param cron                    执行策略
     * @param shardingTotalCount      分片数量
     * @param shardingItemParameters  分片个性化参数
     * @return
     */
    private LiteJobConfiguration createJobConfiguration(final Class<? extends SimpleJob> jobClass,final String cron,final int shardingTotalCount, final String shardingItemParameters){
        //定义作业核心配置
        JobCoreConfiguration.Builder builder = JobCoreConfiguration.newBuilder(jobClass.getName(), cron, shardingTotalCount);
        //设置shardingItemParameters
        if (!StringUtils.isEmpty(shardingItemParameters)){
            builder.shardingItemParameters(shardingItemParameters);
        }
        JobCoreConfiguration jobCoreConfiguration = builder.build();
        //定义SIMPLE类型配置
        SimpleJobConfiguration simpleJobConfig = new SimpleJobConfiguration(jobCoreConfiguration, jobClass.getCanonicalName());
        //定义Lite作业根配置
        LiteJobConfiguration simpleJobRootConfig = LiteJobConfiguration.newBuilder(simpleJobConfig).overwrite(true).build();
        return simpleJobRootConfig;
    }

    /**
     * initMethod:初始化调用 “init”方法
     * @return
     */
    @Bean(initMethod = "init")
    public SpringJobScheduler initSimpleElasticJob(){
        //创建SpringJobScheduler
//        return new SpringJobScheduler(fileBackupJob,coordinatorRegistryCenter,createJobConfiguration(fileBackupJob.getClass(),"0/3 * * * * ?",4,"0=text,1=image,2=radio,3=video"));
        return new SpringJobScheduler(fileBackupJobDb,coordinatorRegistryCenter,createJobConfiguration(fileBackupJobDb.getClass(),"0/3 * * * * ?",4,"0=text,1=image,2=radio,3=video"));
    }
}
